package com.ruoyi.wvp.config;

import com.ruoyi.common.utils.CacheUtils;
import com.ruoyi.wvp.filter.LoggingFilter;
import com.ruoyi.wvp.sdk.monitor.MonitorApi;
import lombok.Getter;
import lombok.Setter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.reactive.function.client.ClientRequest;
import org.springframework.web.reactive.function.client.WebClient;
import org.springframework.web.reactive.function.client.support.WebClientAdapter;
import org.springframework.web.service.invoker.HttpServiceProxyFactory;

@Configuration
@Setter
@Getter
public class MonitorPlatformConfig {

    public static final String TOKEN_KEY = "monitor_admin_token";
    public static final String CACHE_NAME = "monitor_platform";

    @Value("${wvp.surveillance.baseUrl:}")
    private String baseUrl;

    @Value("${wvp.surveillance.userName:}")
    private String userName;

    @Value("${wvp.surveillance.password:}")
    private String password;

    @Value("${wvp.surveillance.loginPath:/login}")
    private String loginPath;

    @Value("${wvp.surveillance.deviceStatusListPath:/deviceStatusListPath}")
    private String deviceStatusListPath;

    @Value("${wvp.surveillance.livePath:/livePath}")
    private String livePath;

    @Value("${wvp.surveillance.projectId:}")
    private String projectId;

    @Bean
    WebClient webClient() {

        return WebClient.builder()
                //添加全局默认请求头
                .defaultHeader("Content-Type", "application/json;charset=utf-8")
                //给请求添加过滤器，添加自定义的认证头
                .filter((request, next) -> {
                    ClientRequest filtered = ClientRequest.from(request)
                            .header("Token", getToken())
                            .build();
                    return next.exchange(filtered);
                })
                .filter(new LoggingFilter())
                .baseUrl(baseUrl).build();

    }

    private String getToken() {
        String token = CacheUtils.get(CACHE_NAME, TOKEN_KEY, String.class);
        if (token == null) {
            // @TODO
            return null;
        }
        return token;
    }

    @Bean
    MonitorApi monitorApi(WebClient client) {
        HttpServiceProxyFactory factory = HttpServiceProxyFactory.
                builder(WebClientAdapter.forClient(client))
                .build();
        return factory.createClient(MonitorApi.class);

    }


}
